package dictcn.com.activity;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.webview.OAuthV1AuthorizeWebView;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.api.AccountAPI;
import com.weibo.sdk.android.api.UsersAPI;
import com.weibo.sdk.android.net.RequestListener;

import dictcn.com.R;
import dictcn.com.control.AccessQqTokenKeeper;
import dictcn.com.control.AccessSinaTokenKeeper;
import dictcn.com.model.AccessQqUserInfo;
import dictcn.com.model.AccessSinaUserId;
import dictcn.com.model.AccessSinaUserInfo;

public class ShareSetting extends Activity {
	
	private RelativeLayout layout_sina;
	private RelativeLayout layout_qq;
	private RelativeLayout layout_renren;
	private TextView txt_sina_login;
	private TextView txt_qq_login;
	private ImageButton imgbtn_share_back;
	
	private static OAuthV1 oauth;
	private static Weibo mWeibo;
	private static Oauth2AccessToken accessToken;
	
	
	private Handler myHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case 1:
				if(accessToken!=null){
					if(!AccessSinaUserInfo.readUserInfo(ShareSetting.this).equals("-1")){
						Toast.makeText(ShareSetting.this, "sina认证成功！", Toast.LENGTH_SHORT).show();
						txt_sina_login.setText(AccessSinaUserInfo.readUserInfo(ShareSetting.this));
					}else{
						Toast.makeText(ShareSetting.this, "sina认证失败！", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case 2:
				Toast.makeText(ShareSetting.this, "信息分享成功！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(ShareSetting.this, "信息分享失败，网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(ShareSetting.this, "网络连接失败！", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_setting);		
		initView();
	}
	
	public void initView(){
		layout_sina=(RelativeLayout)findViewById(R.id.layout_sina_share);
		layout_qq=(RelativeLayout)findViewById(R.id.layout_qq_share);
		layout_renren=(RelativeLayout)findViewById(R.id.layout_renren_share);
		txt_sina_login=(TextView)findViewById(R.id.txt_sina_login);
		txt_qq_login=(TextView)findViewById(R.id.txt_qq_login);
		imgbtn_share_back=(ImageButton)findViewById(R.id.imgbtn_share_back);
		
		imgbtn_share_back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShareSetting.this.finish();
			}
		});
		
		//sina layout listener
		layout_sina.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				CookieSyncManager.createInstance(ShareSetting.this);  
				CookieSyncManager.getInstance().startSync();  
				CookieManager.getInstance().removeAllCookie();
				
				if(txt_sina_login.getText().toString().equals("未绑定")){
					mWeibo=Weibo.getInstance("1825331322", "http://www.sina.com");
					mWeibo.authorize(ShareSetting.this, new SinaAuthDlgListener());
				}else{
					Dialog dlg =new AlertDialog.Builder(ShareSetting.this)
						.setMessage("提示")
						.setTitle("是否取消绑定")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								AccessSinaTokenKeeper.clearSinaToken(ShareSetting.this);
								AccessSinaUserInfo.clearUserInfo(ShareSetting.this);
								txt_sina_login.setText("未绑定");
							}
						})
						.setNegativeButton("取消", null)
						.create();
					dlg.show();				
				}
			}
		});
		
		//qq layout listener
		layout_qq.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(txt_qq_login.getText().toString().trim().equals("未绑定")){
					if(oauth==null)
						oauth=new OAuthV1("null");
						oauth.setOauthConsumerKey("801351500");
						oauth.setOauthConsumerSecret("af525481caa63b51babedaaa8f1d53e5");
					try {
			        	oauth=OAuthV1Client.requestToken(oauth);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
		        	Intent intent = new Intent(ShareSetting.this, OAuthV1AuthorizeWebView.class);
		            intent.putExtra("oauth", oauth);
		            startActivityForResult(intent,123); 
		            
				}else{
					Dialog dlg =new AlertDialog.Builder(ShareSetting.this)
						.setMessage("提示")
						.setTitle("是否取消绑定")
						.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								AccessQqTokenKeeper.clearQqToken(ShareSetting.this);
								AccessQqUserInfo.clearQqUser(ShareSetting.this);
								txt_qq_login.setText("未绑定");
							}
						})
						.setNegativeButton("取消", null)
						.create();
					dlg.show();	
				}
			}
		});
		
		//the init of textview
		if(!AccessSinaUserInfo.readUserInfo(ShareSetting.this).equals("-1"))
			txt_sina_login.setText(AccessSinaUserInfo.readUserInfo(ShareSetting.this));
		
		if(!AccessQqUserInfo.readQqUser(ShareSetting.this).equals("-1"))
			txt_qq_login.setText(AccessQqUserInfo.readQqUser(ShareSetting.this));
	}
	
	
	/*
	 * 下面大部分为腾讯及新浪的用户绑定及用户名的获取信息代码，以后要重构！！！！！！！！
	 */
	//新浪微博登陆认证Oauth2.0
	public class SinaAuthDlgListener implements WeiboAuthListener{
		
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			String token=values.getString("access_token");
			String expires_in=values.getString("expires_in");
			//get the oauth of sina account
			ShareSetting.accessToken=new Oauth2AccessToken(token,expires_in);
			if(ShareSetting.accessToken.isSessionValid()){
				
				AccessSinaTokenKeeper.keepSinaAccessToken(ShareSetting.this, accessToken);				
				AccountAPI accountAPI=new AccountAPI(ShareSetting.accessToken);
				accountAPI.getUid(new RequestListener() {
					
					public void onIOException(IOException arg0) {
						// TODO Auto-generated method stub
						Message msg=new Message();
						msg.what=4;
						ShareSetting.this.myHandler.sendMessage(msg);
					}
					
					public void onError(WeiboException arg0) {
						// TODO Auto-generated method stub
						Message msg=new Message();
						msg.what=4;
						ShareSetting.this.myHandler.sendMessage(msg);
					}
					
					public void onComplete(String arg0) {
						// TODO Auto-generated method stub
						int n=arg0.indexOf(":");
						int m=arg0.indexOf("}");
						AccessSinaUserId.keepUidAccessToken(ShareSetting.this, arg0.substring(n+1,m));
						String uid=AccessSinaUserId.readUidAccessToken(ShareSetting.this);
						UsersAPI usersAPI=new UsersAPI(ShareSetting.accessToken);
						//get the uid of sina
						usersAPI.show(Long.parseLong(uid), new getSinaUserInfoListener());
					}
				});
				
			}
		}

		public void onCancel() {
			// TODO Auto-generated method stub
			
		}

		public void onError(WeiboDialogError arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			ShareSetting.this.myHandler.sendMessage(msg);
		}

		public void onWeiboException(WeiboException arg0) {
			// TODO Auto-generated method stub
			Message msg=new Message();
			msg.what=4;
			ShareSetting.this.myHandler.sendMessage(msg);
		}
	}
	
	//获取新浪登陆用户的用户名
	public class getSinaUserInfoListener implements RequestListener{

		public void onComplete(String arg0) {
			
			//get the screen_name of sina account
			int index=arg0.indexOf("screen_name");
			arg0=arg0.substring(index);
			int index2=arg0.indexOf(",");
			String name=arg0.substring(14,index2-1);
			AccessSinaUserInfo.keepUserInfo(ShareSetting.this, name);		
			ShareSetting.accessToken=AccessSinaTokenKeeper.readSinaAccessToken(ShareSetting.this);
			
			Message msg=new Message();
			msg.what=1;
			ShareSetting.this.myHandler.sendMessage(msg);
		}

		public void onError(WeiboException arg0) {
			// TODO Auto-generated method stub
		}

		public void onIOException(IOException arg0) {
			// TODO Auto-generated method stub
		}
	}
	
	//腾讯用户认证及用户名的获取Oauth1.0
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode==123) {
            if (resultCode==OAuthV1AuthorizeWebView.RESULT_CODE)    {
                oauth=(OAuthV1) data.getExtras().getSerializable("oauth");
                try {
                	//get the oauth of qq account
              	  oauth=OAuthV1Client.accessToken(oauth);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } 
                
                AccessQqTokenKeeper.keepQqAccessToken(ShareSetting.this, oauth);
                Toast.makeText(ShareSetting.this, "qq认证成功",Toast.LENGTH_LONG).show();
              
                //get the nickname of qq account
                UserAPI userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_1);
                   String useInfo;
				try {
					useInfo = userAPI.info(oauth, "json");
					int index=useInfo.indexOf("\"nick\"");
					useInfo=useInfo.substring(index);
					int index2=useInfo.indexOf("\",\"");
					useInfo=useInfo.substring(8,index2);
					AccessQqUserInfo.keepQqUser(ShareSetting.this, useInfo);
	            	txt_qq_login.setText(useInfo);
	            	
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
                userAPI.shutdownConnection();
                
            }else{
            	Toast.makeText(ShareSetting.this, "qq认证失败",Toast.LENGTH_LONG).show();
            }
		}
	}
}
